package com.simple.piger.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.simple.piger.entity.ApplyUser;
import com.simple.piger.entity.CmsSysUserRole;
import com.simple.piger.service.*;
import com.simple.piger.utils.AjaxResult;
import com.simple.piger.utils.IpUtils;
import com.simple.piger.utils.PublicUtil;
import com.simple.piger.constant.AjaxCode;
import com.simple.piger.dto.resp.SysUserRespDto;
import com.simple.piger.entity.CmsSysRole;
import com.simple.piger.entity.CmsSysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/cms")
public class LoginController extends BaseController {
    @Autowired
    private CmsUserService cmsUserService;
    @Autowired
    private CmsSysPermissionService cmsSysPermissionService;
    @Autowired
    private CmsSysRoleService cmsSysRoleService;
    @Autowired
    private CmsSysUserRoleService cmsSysUserRoleService;
    /**
     * 登入
     * @param hashMap
     * @return
     */
    @PostMapping("/login")
    public AjaxResult<String> login(@RequestParam HashMap<String, String> hashMap) {
        AjaxResult<String> ajaxResult = null;
        com.alibaba.fastjson.JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        try {
            ajaxResult = cmsUserService.login(username, password, UUID.randomUUID().toString());
        } catch (Exception e) {
            e.printStackTrace();
            return fail("登入失败");
        }
        if (ajaxResult.success()) {
            setAttribute("userId", ajaxResult.getData());
        }
        return ajaxResult;
    }

    /**
     * 获取用户的帐户信息和权限
     * @Author  donghj
     * @Date    2017/11/20 17:30
     */
    @GetMapping("/user/info/all")
    public AjaxResult getLoginUserInfos() {
        // 获取用户的帐户信息
        String userId = getValueFromSession("userId");
        EntityWrapper<CmsSysUser> ew_cmsSysUser = new EntityWrapper<>();
        ew_cmsSysUser.eq("id", userId);
        CmsSysUser cmsSysUser = cmsUserService.selectOne(ew_cmsSysUser);

        EntityWrapper<CmsSysUserRole> ew = new EntityWrapper<>();
        ew.eq("user_id", userId);
        List<CmsSysUserRole> list = cmsSysUserRoleService.selectList(ew);
        String role = "0";
        for (CmsSysUserRole cmsSysUserRole : list) {
            if (Integer.valueOf(1).equals(cmsSysUserRole.getRoleId())) {
                role = "1";
            } else if (Integer.valueOf(40).equals(cmsSysUserRole.getRoleId())) {
                role = "2";
            } else if (Integer.valueOf(41).equals(cmsSysUserRole.getRoleId())) {
                role = "3";
            } else if (Integer.valueOf(42).equals(cmsSysUserRole.getRoleId())) {
                role = "4";
            }
        }

        JSONObject userInfo = new JSONObject();
        userInfo.put("username", cmsSysUser.getUsername());
        userInfo.put("name", cmsSysUser.getName());
        userInfo.put("role", role);
        userInfo.put("lastLogin", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cmsSysUser.getLastLogin()));
        // 获取用户关联角色所拥有的模块、菜单和按钮权限
        JSONArray treeJson = cmsSysPermissionService.getUserRigthsById(userId);
        // 获取用户登录IP地址
        String ip = null;
        try {
            ip = IpUtils.getIp(this.getRequest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取用户的系统配置
        JSONObject jsonObject = new JSONObject();
        // 构建返回数据
        LinkedHashMap<String, Object> rtn_map = new LinkedHashMap<>();
        rtn_map.put("user_info", userInfo);
        rtn_map.put("user_permissions", treeJson);
        rtn_map.put("user_login_ip", ip);
        rtn_map.put("user_sys_def", jsonObject);
        return success(rtn_map);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public AjaxResult logout() {
        getSession().invalidate();
        return success();
    }

    /**
     * 用户修改密码
     */
    @PostMapping("/editPWD")
    public AjaxResult editPWD(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        // 获取原密码和新密码
        String old_password = jsonObject.getString("old_password");
        String new_password = jsonObject.getString("new_password");
        // 获取用户ID
        String userId = getValueFromSession("userId");
        AjaxCode ajaxCode = cmsUserService.editPWD(userId, old_password, new_password);
        return ajaxCode == null ? success() : fail(ajaxCode);
    }

    /**
     * 根据用户主键获取用户信息和用户所拥有的角色信息
     */
    @GetMapping("/user/info")
    public AjaxResult getUserById() {
        String userId = getValueFromSession("userId");
        // 获取用户信息
        CmsSysUser cmsSysUser = cmsUserService.selectById(userId);
        SysUserRespDto sysUser = new SysUserRespDto();
        BeanUtils.copyProperties(cmsSysUser, sysUser);
        // 获取角色信息
        List<CmsSysRole> cmsSysRoles = cmsSysRoleService.getRoleListByUserId(userId);
        // 构建返回数据
        LinkedHashMap<String, Object> rtn_map = new LinkedHashMap<>();
        rtn_map.put("user_info", sysUser);
        rtn_map.put("user_roles", cmsSysRoles);
        return success(rtn_map);
    }

    /**
     * 用户注册接口
     * @param hashMap
     * @return
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        // 获取原密码和新密码
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        String roleId = jsonObject.getString("roleId");
        String companyId = jsonObject.getString("companyId");
        AjaxCode ajaxCode = cmsUserService.register(username, password, roleId, companyId);
        return ajaxCode == null ? success() : fail(ajaxCode);
    }

    @Autowired
    private ApplyUserService applyUserService;

    /**
     * 用户更新信息接口
     * @param hashMap
     * @return
     */
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        // 获取原密码和新密码
        String userId = getValueFromSession("userId");
        String username = jsonObject.getString("name");
        String phone = jsonObject.getString("phone");

        CmsSysUser cmsSysUser = cmsUserService.selectById(userId);
        EntityWrapper<ApplyUser> auEw = new EntityWrapper<>();
        auEw.eq("cms_sys_user_id", cmsSysUser.getId());
        ApplyUser applyUser = applyUserService.selectOne(auEw);

        cmsSysUser.setName(username);
        cmsSysUser.setPhone(phone);

        applyUser.setName(username);
        applyUser.setPhone(phone);

        cmsSysUser.updateById();
        applyUser.updateById();
        return success();
    }
}
